<template>
  <div class="container" @mouseleave="stopDrag" ref="container">
    <div class="main-table" :style="{ height: `${currentPosition}px` }">
      <slot></slot>
    </div>
    <div class="draggable">
      <div class="move-header" @mousedown.stop="startDrag"></div>
      <div class="son-table" ref="sonHeight"><slot name="son"></slot></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, Ref, onMounted, onUnmounted } from 'vue';
const emit = defineEmits(['changedAreaHeight']);
const container: Ref<HTMLElement | null> = ref(null);
const sonHeight: Ref<HTMLElement | null> = ref(null);
let currentPosition: Ref<number> = ref(400);
let start = 0;
let isDragging = false;
onMounted(() => {
  if (container.value) {
    container.value.addEventListener('mousemove', drag);
    container.value.addEventListener('mouseup', stopDrag);
  }
  emitEvent();
});
onUnmounted(() => {
  if (container.value) {
    container.value.removeEventListener('mousemove', drag);
    container.value.removeEventListener('mouseup', stopDrag);
  }
});

function startDrag(event: MouseEvent) {
  isDragging = true;
  start = event.clientY;
}

function stopDrag() {
  // 如果并未滑动，直接return，不触发该事件
  if (!isDragging) return;
  isDragging = false;
  emitEvent();
}

function emitEvent() {
  emit('changedAreaHeight', {
    mainHeight: currentPosition.value,
    sonHeight: sonHeight.value?.clientHeight
  });
}

function drag(event: MouseEvent) {
  if (!isDragging) return;
  if (event.clientY > 700 || event.clientY < 200) return;
  currentPosition.value += event.clientY - start;
  start = event.clientY;
}
</script>

<style scoped lang="less">
.container {
  width: 100vw;
  height: 85vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: white;
  .main-table {
    width: 100vw;
    bottom: 30px;
    overflow-x: scroll;
    display: flex;
    align-items: center;
  }
  .draggable {
    flex-grow: 1;
    width: 100vw;
    height: 40px;
    cursor: pointer;
    .move-header {
      height: 40px;
      background-color: #dfdfdf;
      &:hover {
        box-shadow: 10px 0 10px rgba(0, 0, 0, 0.5);
      }
    }
    .son-table {
      width: 100vw;
      height: 100%;
      overflow-x: scroll;
    }
  }
}
</style>
